<template>
    <f7-page class="common-page has-bottom-btns hntsh">
        <f7-navbar>
            <f7-nav-left>
                <f7-link back icon-material="chevron_left" force></f7-link>
            </f7-nav-left>
            <f7-nav-title>作业前准备</f7-nav-title>
            <f7-nav-right></f7-nav-right>
        </f7-navbar>
        <div class="common-page-content">
            <v-picture-list :props="{ name: 'customName' }" :disabled="!canEdit" listName="list1" title="现场照片"
                typeCode="EQM_MOBILE_ZYQZB" :dataKey="jobId" ref="list1"></v-picture-list>
            <v-accordion title="操作人员">
                <person-list :list="models.mobileJobPersonList" :isDisabled="!canEdit"
                    @delete="deletePerson"></person-list>
                <f7-button fill class="submit-btn person-btn" @click="showPerson = true" v-if="canEdit">
                    <f7-icon f7="plus" size="18px" style="margin-right: 5px"></f7-icon>
                    添加人员
                </f7-button>
            </v-accordion>
        </div>
        <f7-toolbar position="bottom" no-shadow class="fff" v-if="canEdit">
            <f7-button fill class="submit-btn plain-btn" @click="fnSubmit('draft')">保存</f7-button>
            <f7-button fill class="submit-btn" @click="fnSubmit('submit')">提交</f7-button>
        </f7-toolbar>
        <!-- 选择人员 -->
        <person-popup v-model="showPerson" busiKey="personPkid"
            url="/app/equipment/eqmPrjJobPerson/query" @save="surePerson"
            :chooseArr="models.mobileJobPersonList"
            :extraParams="{ engineeId: engineeId,useType:0 }"></person-popup>
    </f7-page>
</template>

<script>
import PersonList from "../../components/PersonList.vue";
import PersonPopup from "../../components/PersonPopup.vue";
import controller from "@/libs/framework/controller";

export default class instance extends controller {
    onInit() {
        this.context.registerId = this.$f7route.query.registerId;
        this.context.engineeCode = this.$f7route.query.engineeCode;
        this.context.engineeId = this.$f7route.query.engineeId;
        this.context.pageAction = this.$f7route.query.pageAction;
        this.context.recreate = this.$f7route.query.recreate;
    }
    onBeforeInit() {
        this.urls = {// 变更登记的时候 第一个请求是为了获取新的id 第二个请求是为了获取之前的一条数据
            model: ["/app/equipment/eqmMobileJob/getEntity", "/app/equipment/eqmMobileJob/getEntity"],
        };
    }
    onBeforeQuery(type, conditions, params) {
        if (type == 'form' && this.context.recreate) {// 变更登记
            params.jobId = '';
            params.pageAction = 'create'
        }
    }
    onAfterQuery(type, isSuccess, result) {
        if (type == 'form') {
            this.context.jobId = result.models.model.jobId;
        } else if (type == 'form$1' && this.context.recreate) {
            this.context.oldJobId = result.models.model.jobId;
            this.vm.handleCopyAttachment(result.models.model.jobId);
        }
        return result;
    }
    mixin() {
        return {
            data() {
                return {
                    oldJobId:'',// 变更登记时候的原来数据
                    jobId: '',// 变更登记的时候的唯一表示
                    models: {
                        model: {

                        },
                        mobileJobPersonList: []
                    },
                    registerId: '',
                    engineeId:'',
                    engineeCode: '',
                    showPerson: false,
                    pageAction: '',
                    recreate: false,// 变更登记
                    first:true,// 变更登记 点击保存 首次是 create  不返回页面再次点击保存是edit
                    picListDone: false,// 获取附件配置完成
                };
            },
            components: {
                PersonPopup,
                PersonList,
            },
            computed: {
                canEdit() {
                    return this.pageAction != 'view';
                }
            },
            methods: {
                async fnSubmit(jobStatus) {
                    // 校验附件必传项
                    let flag1 = this.$refs.list1.getUploadedCount();
                    if (!flag1) return this.$toast("请上传现场照片附件");
                    if (this.models.mobileJobPersonList.length == 0 && jobStatus == 'submit') {
                        return this.$toast("请添加操作人员");
                    }
                    let check = true;
                    let repeatPerson = [];
                    if (jobStatus == 'submit') {
                        this.$f7.preloader.show();
                        const res = await this.checkPerson();
                        check = res.success;
                        if(!res.success){
                            repeatPerson = res.parameters?.data;
                        }
                    }
                    this.$f7.preloader.show();
                    if (check) {
                        this.models.model.jobId = this.jobId;
                        let model = {
                            jobId: this.models.model.jobId,
                            jobStatus: jobStatus,
                            registerId: this.registerId
                        }
                        this.models.mobileJobPersonList.forEach(element => {
                            element.jobId = this.models.model.jobId;
                            element.jobPersonId = this.recreate ? '' : element.jobPersonId;
                        });
                        this.$f7.request.post(
                            `/equipment/eqmMobileJob/save`, {
                            pageAction: this.recreate && this.first? 'create' : this.pageAction,
                            jobId: this.models.model.jobId,
                            model: model,
                            mobileJobPersonList: this.models.mobileJobPersonList
                        },
                            (r) => {
                                this.$f7.preloader.hide();
                                r = JSON.parse(r);
                                if (r && r.success) {
                                    this.first = false;
                                    if (jobStatus == 'submit') {
                                        this.$f7.dialog.alert(`提交成功`, () => {
                                            this.$f7router.back();
                                        })
                                    } else {
                                        this.pageAction = 'edit'
                                        this.$toast("保存成功")
                                    }
                                } else {
                                    this.$toast(r.message || "提交失败，请稍后重试");
                                }
                            },
                            (err) => { this.$f7.preloader.hide();}
                        );
                    }else{
                        this.$f7.preloader.hide();
                        const nameStr = repeatPerson.map(v=>v.personName).join("、")
                        this.$toast(`${nameStr}已关联进场设备，请重新选择`)
                    }
                },
                // 作业前准备提交前要校验 人员是否关联设备 没有关联的才可以选择
                checkPerson() {
                    return new Promise((resolve, reject) => {
                        this.$f7.request.post(
                            `/equipment/eqmMobileJob/validate`,
                            {
                                oldJobId:this.recreate?this.oldJobId:'',
                                engineeId: this.engineeId,
                                mobileJobPersonList: this.models.mobileJobPersonList,
                            },
                            (r) => {
                                r = JSON.parse(r);
                                if (r && r.success) {
                                    resolve(r)
                                } else {
                                    resolve(r)
                                }
                            },
                            (err) => { reject(false) }
                        );
                    })
                },

                //选择人员
                surePerson(personList) {
                    this.models.mobileJobPersonList = JSON.parse(JSON.stringify(personList));
                },
                deletePerson(index) {
                    this.models.mobileJobPersonList.splice(index, 1);
                },
                // 选择一个退场的设备后 要将之前设备的附件全部复制一套到新的进场
                handleCopyAttachment(oldJobId) {
                    let arr = ['AQJY', 'JSJD'];
                    let pendingTasks = arr.length;
                    arr.forEach(item => {
                        this.copyAttachment(oldJobId, item, this.jobId, item).then(r => {
                            pendingTasks--;
                            if (pendingTasks == 0) {
                                this.$refs.list1.getFileList(true);
                            }
                        })
                    });
                },
                // 复制附件
                copyAttachment(oldDataKey, oldBizType, newDataKey, newBizType, listName) {
                    return new Promise((resolve, reject) => {
                        this.$f7.request.post(
                            `/app/mobileApi/base/fileupload/copyAttachment`, {
                            oldDataKey: oldDataKey,
                            oldBizType: oldBizType,
                            newDataKey: newDataKey,
                            newBizType: newBizType
                        },
                            (r) => {
                                r = JSON.parse(r);
                                if (r && r.success) {
                                    resolve(true);
                                } else {
                                    reject();
                                }
                            },
                            (err) => {
                                reject(err)
                            }
                        );
                    })

                },
            },
        };
    }
}
</script>

<style lang="less" scoped>
@import url("../../../../../../assets/css/commonPage.less");
@deep: ~">>>";

@{deep} .v-workflow-list {
    padding: 0 16px;
}

@{deep}.accordion .accordion-item>.item-link>.item-content {
    padding-left: 16px !important;
}

@{deep}.accordion.accordion-list {
    background-color: #fff;
    margin-bottom: 10px;
}

.person-btn {
    background: #f5f9ff;
    border-radius: 24px;
    color: #3385ff;
    margin-bottom: 20px;
}
</style>
